package com.juc.learn.nonfairlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName:LSaleTicket
 * Package:com.juc.learn.learnlock_2
 * Description:
 *
 * @Author:@郭先森
 * @Create:2025/7/26 - 15:55
 * @Version:v1.0
 */
public class LSaleTicket {
    private int number=30;
    //创建可重入锁,调用的是无参构造，默认是一个非公平锁，还能传入一个Boolean的参数，表示创建的是公平锁还是非公平锁
    //非公平锁就是线程1都卖了
    //private final Lock lock = new ReentrantLock();
    private final Lock lock = new ReentrantLock(true);
    //公平锁效率相对低
    //非公平锁效率相对高
    public void sale(){
        lock.lock();//上锁
        try {
            if(number>0){
                System.out.println(Thread.currentThread().getName()+"卖了第"+number--+"张票");
            }
        }finally {//避免出现异常无法释放锁
            lock.unlock();//释放锁
        }

    }
}
